package com.qf.userweb.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.userweb.entity.LoginUser;
import com.qf.userweb.entity.PageVO;
import com.qf.userweb.entity.User;
import com.qf.userweb.entity.UserDTO;
import com.qf.userweb.service.UserService;
import com.qf.userweb.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;


@RestController
@RequestMapping("/api/user")
@Slf4j
@CrossOrigin//后端解决跨域，后期前端配置跨域
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginUser loginUser, HttpSession  session) {
        log.debug("用户登录：{}", loginUser);
        User user = userService.login(loginUser);
        session.setAttribute("user", user);
        return R.ok(user);
    }

    /**
     * 查询全部用户信息v1 无参
     * 查询全部用户信息v2 分页
     * 查询全部用户信息v3 分页+搜索查
     */
    @GetMapping("/list")
    public R list(UserDTO userDTO) {
        // 防止userDTO为null的情况
        if (userDTO == null) {
            userDTO = new UserDTO();
        }

        // 设置默认分页参数，防止pageNum或pageSize为null
        if (userDTO.getPageNum() == null) {
            userDTO.setPageNum(1);
        }
        if (userDTO.getPageSize() == null) {
            userDTO.setPageSize(10);
        }
        PageHelper.startPage(userDTO.getPageNum(), userDTO.getPageSize());
        List<User> list = userService.list(userDTO);
        if (list == null || list.size() == 0) {
            return R.fail("没有用户信息");
        }
        PageInfo<User> pageInfo = new PageInfo<>(list);
        PageVO pageVO = new PageVO();
        pageVO.setPageNum(pageInfo.getPageNum());
        pageVO.setPageSize(pageInfo.getPageSize());
        pageVO.setTotal(pageInfo.getTotal());
        pageVO.setPages(pageInfo.getPages());
        pageVO.setList(pageInfo.getList());
        return R.ok(pageVO);
    }

    /**
     * 批量删除
     */
    @GetMapping("/del/batch")
    public R batchDelete(@RequestParam List<Integer> ids) {
        log.debug("批量删除用户ids:{}", ids);
        int count = userService.batchDelete(ids);
        if (count == 0) {
            return R.fail("删除失败");
        }
        return R.ok(count);
    }

    /**
     * 添加 用户
     */
    @PostMapping("/add")
    public R add(@RequestBody User user) {
        log.debug("添加用户：{}", user);
        int count = userService.add(user);
        if (count == 0) {
            return R.fail("添加失败");
        }
        return R.ok(count);
    }

    @GetMapping("/logout")
    public R logout(HttpSession session) {
        //销毁session
        session.invalidate();
        return R.ok();
    }
}
